package org.jeecg.modules.business.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.business.dto.BusMarketAgreementCheckInRecordDto;
import org.jeecg.modules.business.entity.*;
import org.jeecg.modules.business.enums.AgreementCommonEnum;
import org.jeecg.modules.business.enums.AgreenmentAccountStatus;
import org.jeecg.modules.business.enums.AgreenmentCheckStatus;
import org.jeecg.modules.business.service.*;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.rooms.service.CesRoomLayoutServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

import static kotlin.reflect.jvm.internal.impl.builtins.StandardNames.FqNames.list;

/**
 * @Description: 协议单位
 * @Author: jeecg-boot
 * @Date:   2023-03-25
 * @Version: V1.0
 */
@Api(tags="协议单位")
@RestController
@RequestMapping("/business/busMarketAgreementUnit")
@Slf4j
public class BusMarketAgreementUnitController extends JeecgController<BusMarketAgreementUnit, IBusMarketAgreementUnitService> {
	@Autowired
	private IBusMarketAgreementUnitService busAgreementUnitService;

	 @Autowired
	 private IBusHotelService busHotelService;

	@Autowired
	private IBusMarketAgreementCheckInRecordService busMarketAgreementCheckInRecordService;

	@Autowired
	private IBusMarketAgreementCustomerService busMarketAgreementCustomerService;

	@Autowired
	private IBusMarketAgreementCustomerHousePriceService busMarketAgreementCustomerHousePriceService;

	@Resource
	private CesRoomLayoutServiceImpl cesRoomLayoutService;

	/**
	 * 分页列表查询
	 *
	 * @param busMarketAgreementUnit
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "协议单位-分页列表查询")
	@ApiOperation(value="协议单位-分页列表查询", notes="协议单位-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BusMarketAgreementUnit>> queryPageList(BusMarketAgreementUnit busMarketAgreementUnit,
															   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															   HttpServletRequest req) {
		QueryWrapper<BusMarketAgreementUnit> queryWrapper = QueryGenerator.initQueryWrapper(busMarketAgreementUnit, req.getParameterMap());
		Page<BusMarketAgreementUnit> page = new Page<BusMarketAgreementUnit>(pageNo, pageSize);
		String keyWord = req.getParameter("keyWord");
		if(oConvertUtils.isNotEmpty(keyWord)){
			queryWrapper.and(i -> i.like("customer_name",keyWord)
					.or().like("customer_no",keyWord)
					.or().like("contacts_name",keyWord)
					.or().like("phone",keyWord));
		}
		IPage<BusMarketAgreementUnit> pageList = busAgreementUnitService.page(page, queryWrapper);
		pageList.getRecords().forEach(item->{
			BusHotel hotle = busHotelService.getById(item.getHotelId());
			if (hotle != null) {
				item.setHotelName(hotle.getName());
			}
		});
		return Result.OK(pageList);
	}


	/**
	 * 分页列表查询
	 *
	 * @param busMarketAgreementCheckInRecordDto
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "协议单位-入住记录-分页列表查询")
	@ApiOperation(value="协议单位-入住记录-分页列表查询", notes="协议单位-入住记录-分页列表查询")
	@GetMapping(value = "/listCheckInRecord")
	public Result<IPage<BusMarketAgreementCheckInRecordDto>> queryPageCheckInRecordList(BusMarketAgreementCheckInRecordDto busMarketAgreementCheckInRecordDto,
																						@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																						@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																						HttpServletRequest req) {
		Page<BusMarketAgreementCheckInRecordDto> page = new Page<BusMarketAgreementCheckInRecordDto>(pageNo, pageSize);
		String startDate = busMarketAgreementCheckInRecordDto.getStartDate() + " 00:00:00";
		String endDate = busMarketAgreementCheckInRecordDto.getEndDate() + " 23:59:59";
		IPage<BusMarketAgreementCheckInRecordDto> pageList = busMarketAgreementCheckInRecordService
				.getCheckInRecord(page,busMarketAgreementCheckInRecordDto.getAgreementId(), startDate, endDate, busMarketAgreementCheckInRecordDto.getRoomNumber(), busMarketAgreementCheckInRecordDto.getCustomerName());

		pageList.getRecords().forEach(item->{
			//当前客户有选择具体客户协议，则房价根据客户协议处理
			if (item.getAgreementCustomerId() != null && !item.getAgreementCustomerId().equals("")){
				BigDecimal realPrice = getRealPrice(item);
				item.setHousePrice(realPrice);
				item.setTotalPrice(realPrice);
			}
		});
		return Result.OK(pageList);
	}

	public BigDecimal getRealPrice(BusMarketAgreementCheckInRecordDto item){
		long realPrice = 0;
		BusMarketAgreementCustomer busMarketAgreementCustomer = busMarketAgreementCustomerService.getById(item.getAgreementCustomerId());
		if (busMarketAgreementCustomer != null ){
			//使用固定折扣，则房价=门市价*固定折扣
			if (busMarketAgreementCustomer.getFixedDiscount() == AgreementCommonEnum.yes.getKey()){
				realPrice = Math.round(item.getHousePrice().doubleValue() * (busMarketAgreementCustomer.getDiscount().doubleValue()/100));
			}else{
				//获取到协议房价表
				QueryWrapper<BusMarketAgreementCustomerHousePrice> queryWrapper = new QueryWrapper<BusMarketAgreementCustomerHousePrice>();
				queryWrapper.eq("customer_id",item.getAgreementCustomerId());
				queryWrapper.eq("layout_id",item.getLayoutId());
				BusMarketAgreementCustomerHousePrice busMarketAgreementCustomerHousePrice = busMarketAgreementCustomerHousePriceService.getOne(queryWrapper);
				if(busMarketAgreementCustomerHousePrice != null && busMarketAgreementCustomerHousePrice.getDiscount() !=null){
					realPrice = Math.round(item.getHousePrice().doubleValue() * (busMarketAgreementCustomerHousePrice.getDiscount().doubleValue()/100));
				}
			}
		}
		return  BigDecimal.valueOf(realPrice);
	}

	/**
	 *   添加
	 *
	 * @param busMarketAgreementUnit
	 * @return
	 */
	@AutoLog(value = "协议单位-添加")
	@ApiOperation(value="协议单位-添加", notes="协议单位-添加")
	//@RequiresPermissions("business:bus_agreement_unit_info:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BusMarketAgreementUnit busMarketAgreementUnit) {
		busMarketAgreementUnit.setDelFlag(CommonConstant.DEL_FLAG_0);
		busMarketAgreementUnit.setAccountStatus(AgreenmentAccountStatus.normal.getKey());
		busMarketAgreementUnit.setCheckStatus(AgreenmentCheckStatus.unaudited.getKey());
		if (busMarketAgreementUnit.getTenantId() == null || busMarketAgreementUnit.getTenantId().equals("")) {
			LoginUser user = TokenUtils.getAuthUser();
			if (user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")) {
				busMarketAgreementUnit.setTenantId(user.getRelTenantIds());
			} else {
				throw new JeecgBootException("当前登录人租户信息错误");
			}
		}
		//获取当前最大账号
		String _maxAccount = busAgreementUnitService.getMaxAccount();
		Integer _num = Integer.parseInt(_maxAccount.split("A")[1]) + 1;
		String _account = "A" + String.format( "%05d", _num);
		busMarketAgreementUnit.setAccountNo(_account);
		busAgreementUnitService.save(busMarketAgreementUnit);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param busMarketAgreementUnit
	 * @return
	 */
	@AutoLog(value = "协议单位-编辑")
	@ApiOperation(value="协议单位-编辑", notes="协议单位-编辑")
	//@RequiresPermissions("business:bus_agreement_unit_info:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BusMarketAgreementUnit busMarketAgreementUnit) {
//		busAgreementUnitService.updateById(busAgreementUnit);
		if(busMarketAgreementUnit.getTenantId() == null || busMarketAgreementUnit.getTenantId().equals("")){
			LoginUser user = TokenUtils.getAuthUser();
			if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				busMarketAgreementUnit.setTenantId(user.getRelTenantIds());
			} else {
				throw new JeecgBootException("当前登录人租户信息错误");
			}
		}
		//客户编号校验
		LambdaQueryWrapper<BusMarketAgreementUnit> queryWrapper = new LambdaQueryWrapper<BusMarketAgreementUnit>();
		queryWrapper.eq(BusMarketAgreementUnit::getCustomerNo,busMarketAgreementUnit.getCustomerNo());
		if (StringUtils.isNotBlank(busMarketAgreementUnit.getId())) {
			// 编辑页面校验
			queryWrapper.ne(BusMarketAgreementUnit::getId,busMarketAgreementUnit.getId());
		}
		long num = busAgreementUnitService.count(queryWrapper);
		if (num != 0) {
			// 该值不可用
			return Result.error("客户编号已存在！");
		}
		BusMarketAgreementUnit editModel = busAgreementUnitService.getById(busMarketAgreementUnit.getId());
		editModel.setCustomerName(busMarketAgreementUnit.getCustomerName());
		editModel.setCustomerShortName(busMarketAgreementUnit.getCustomerShortName());
		editModel.setSystemType(busMarketAgreementUnit.getSystemType());
		editModel.setCustomerNo(busMarketAgreementUnit.getCustomerNo());
		editModel.setContactsName(busMarketAgreementUnit.getContactsName());
		editModel.setCustomerType(busMarketAgreementUnit.getCustomerType());
		editModel.setSellerId(busMarketAgreementUnit.getSellerId());
		editModel.setPhone(busMarketAgreementUnit.getPhone());
		editModel.setStatus(busMarketAgreementUnit.getStatus());
		editModel.setRegion(busMarketAgreementUnit.getRegion());
		editModel.setPostalCode(busMarketAgreementUnit.getPostalCode());
		editModel.setAddress(busMarketAgreementUnit.getAddress());
		editModel.setCompanyPhone(busMarketAgreementUnit.getCompanyPhone());
		editModel.setFax(busMarketAgreementUnit.getFax());
		editModel.setCustomerSource(busMarketAgreementUnit.getCustomerSource());
		editModel.setHomepage(busMarketAgreementUnit.getHomepage());
		editModel.setEmail(busMarketAgreementUnit.getEmail());
		editModel.setCustomerIndustry(busMarketAgreementUnit.getCustomerIndustry());
		editModel.setLeaveTime(busMarketAgreementUnit.getLeaveTime());
		busAgreementUnitService.updateById(editModel);
		return Result.OK("编辑成功!");
	}

	/**
	 *  编辑
	 *
	 * @param busMarketAgreementUnit
	 * @return
	 */
	@AutoLog(value = "协议单位-编辑")
	@ApiOperation(value="协议单位-编辑", notes="协议单位-编辑")
	//@RequiresPermissions("business:bus_agreement_unit_info:edit")
	@RequestMapping(value = "/editOther", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> editOther(@RequestBody BusMarketAgreementUnit busMarketAgreementUnit) {
//		busAgreementUnitService.updateById(busAgreementUnit);
		if(busMarketAgreementUnit.getTenantId() == null || busMarketAgreementUnit.getTenantId().equals("")){
			LoginUser user = TokenUtils.getAuthUser();
			if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
				busMarketAgreementUnit.setTenantId(user.getRelTenantIds());
			} else {
				throw new JeecgBootException("当前登录人租户信息错误");
			}
		}
		//客户编号校验
		LambdaQueryWrapper<BusMarketAgreementUnit> queryWrapper = new LambdaQueryWrapper<BusMarketAgreementUnit>();
		queryWrapper.eq(BusMarketAgreementUnit::getCustomerNo,busMarketAgreementUnit.getCustomerNo());
		if (StringUtils.isNotBlank(busMarketAgreementUnit.getId())) {
			// 编辑页面校验
			queryWrapper.ne(BusMarketAgreementUnit::getId,busMarketAgreementUnit.getId());
		}
		long num = busAgreementUnitService.count(queryWrapper);
		if (num != 0) {
			// 该值不可用
			return Result.error("客户编号已存在！");
		}
		BusMarketAgreementUnit editModel = busAgreementUnitService.getById(busMarketAgreementUnit.getId());
		editModel.setBookkeeping(busMarketAgreementUnit.getBookkeeping());
		editModel.setRemarks(busMarketAgreementUnit.getRemarks());
		editModel.setReception(busMarketAgreementUnit.getReception());
		editModel.setCommission(busMarketAgreementUnit.getCommission());
		editModel.setBookkStatus(busMarketAgreementUnit.getBookkStatus());
		busAgreementUnitService.updateById(editModel);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "协议单位-通过id删除")
	@ApiOperation(value="协议单位-通过id删除", notes="协议单位-通过id删除")
	//@RequiresPermissions("business:bus_agreement_unit_info:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		busAgreementUnitService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "协议单位-批量删除")
	@ApiOperation(value="协议单位-批量删除", notes="协议单位-批量删除")
	//@RequiresPermissions("business:bus_agreement_unit_info:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.busAgreementUnitService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "协议单位-通过id查询")
	@ApiOperation(value="协议单位-通过id查询", notes="协议单位-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BusMarketAgreementUnit> queryById(@RequestParam(name="id",required=true) String id) {
		BusMarketAgreementUnit busMarketAgreementUnit = busAgreementUnitService.getById(id);
		if(busMarketAgreementUnit ==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(busMarketAgreementUnit);
	}

	 /**
	  * 列表查询
	  *
	  * @param busMarketAgreementUnit
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "协议单位-列表查询")
	 @ApiOperation(value="协议单位-列表查询", notes="协议单位-列表查询")
	 @GetMapping(value = "/queryList")
	 public Result<List<BusMarketAgreementUnit>> queryList(BusMarketAgreementUnit busMarketAgreementUnit, HttpServletRequest req) {
		 QueryWrapper<BusMarketAgreementUnit> queryWrapper = QueryGenerator.initQueryWrapper(busMarketAgreementUnit, req.getParameterMap());
		 LoginUser user = TokenUtils.getAuthUser();
		 if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
			 queryWrapper.eq("tenant_id",user.getRelTenantIds());
		 }
		 queryWrapper.eq("del_flag",0);
		 List<BusMarketAgreementUnit> list = busAgreementUnitService.list(queryWrapper);
		 return Result.OK(list);
	 }

	/**
	 *
	 */
	@ApiOperation(value="所有协议单位-包含最新的方案", notes="所有协议单位-包含最新的方案")
	@GetMapping(value = "/getAgreementUnitsDetail")
	public Result<List<BusMarketAgreementUnit>> getAgreementUnitsDetail (BusMarketAgreementUnit busMarketAgreementUnit) {
		QueryWrapper<BusMarketAgreementUnit> queryWrapper = new QueryWrapper<>();
		LoginUser user = TokenUtils.getAuthUser();
		if(user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")){
			queryWrapper.eq("tenant_id",user.getRelTenantIds());
		}
		queryWrapper.eq("del_flag",0);
		List<BusMarketAgreementUnit> agreementUnitList = busAgreementUnitService.list(queryWrapper);
		agreementUnitList.forEach(e -> {
			BusMarketAgreementCustomer firstAgreementCustomer = busMarketAgreementCustomerService.getOne(Wrappers
					.<BusMarketAgreementCustomer>lambdaQuery().eq(BusMarketAgreementCustomer::getAgreementId, e.getId())
					.orderByDesc(BusMarketAgreementCustomer::getCreateTime).last("LIMIT 1"));
			e.setMarketAgreementCustomer(firstAgreementCustomer);
		});
		return Result.OK(agreementUnitList);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param busMarketAgreementUnit
    */
    //@RequiresPermissions("business:bus_agreement_unit_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BusMarketAgreementUnit busMarketAgreementUnit) {
        return super.exportXls(request, busMarketAgreementUnit, BusMarketAgreementUnit.class, "协议单位");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("business:bus_agreement_unit_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BusMarketAgreementUnit.class);
    }

}
